package com.example.demo.repository.support;

import com.example.demo.context.Context;
import com.example.demo.context.CurrentOperator;
import com.example.demo.entity.BaseEntity;
import com.example.demo.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;

/**
 *@Description
 *@Author Levi
 *@Date 2019/4/23-16:53
*/
@Slf4j
@SuppressWarnings("ALL")
public class MySimpleRepository<T extends BaseEntity, ID> extends SimpleJpaRepository<T, ID> {

    private final JpaEntityInformation<T, ?> entityInformation;
    private final EntityManager em;

    @Autowired
    public MySimpleRepository(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);
        this.entityInformation = entityInformation;
        this.em = entityManager;
    }

    @Override
    @Transactional
    public <S extends T> S save(S entity) {
        CurrentOperator currentOperator = Context.currentContext().getCurrentOperator();
        if(currentOperator == null){
            currentOperator = new CurrentOperator();
            currentOperator.setId(1L);
        }
        if (this.entityInformation.isNew(entity)) {
            entity.setId(NumberUtil.randomAbsLong());
            entity.setInsertOperatorId(currentOperator.getId());
            entity.setUpdateOperatorId(currentOperator.getId());
            this.em.persist(entity);
            return entity;
        } else {
            entity.setUpdateOperatorId(currentOperator.getId());
            return this.em.merge(entity);
        }
    }
}